﻿namespace SimpleX.RBAC;

public class ModuleService : DbRepository<SysMenu>, IModuleService
{
    /// <inheritdoc/>
    public async Task<SqlSugarPagedList<SysMenu>> Page(ModulePageInput input)
    {
        var query = Context.Queryable<SysMenu>()
                         .Where(it => it.Category == CateGoryConst.Menu_MODULE)//模块
                         .WhereIF(!string.IsNullOrEmpty(input.SearchKey), it => it.Title.Contains(input.SearchKey))//根据关键字查询
                         .OrderByIF(!string.IsNullOrEmpty(input.SortField), $"{input.SortField} {input.SortOrder}")
                         .OrderBy(it => it.SortCode);//排序
        var pageInfo = await query.ToPagedListAsync(input.Current, input.Size);//分页
        return pageInfo;
    }

    /// <inheritdoc />
    public async Task Add(ModuleAddInput input)
    {
        var result = await CheckInput(input);//检查参数
        if (result != "OK")
        {
            Unify.SetError(result);
            return;
        }
        var sysResource = input.Adapt<SysMenu>();//实体转换
        await InsertAsync(sysResource);
    }

    /// <inheritdoc />
    public async Task Edit(ModuleEditInput input)
    {
        var result = await CheckInput(input);//检查参数
        if (result != "OK")
        {
            Unify.SetError(result);
            return;
        }
        var sysResource = input.Adapt<SysMenu>();//实体转换
        await UpdateAsync(sysResource);
    }

    /// <inheritdoc />
    public async Task Delete(List<BaseIdInput> input)
    {
        //获取所有ID
        var ids = input.Select(it => it.Id).ToList();
        if (ids.Count > 0)
        {
            var menus = await GetListAsync(x => ids.Contains(x.Id));

            //查找内置模块
            var system = menus.Where(it => it.Code == "system").FirstOrDefault();
            if (system != null)
                throw new Exception($"不可删除系统内置模块:{system.Title}");

            var result = await itenant.UseTranAsync(async () =>
            {
                await DeleteByIdsAsync(ids.Cast<object>().ToArray());
                await Context.Deleteable<SysRelation>().Where(x => ids.Contains(x.ObjectId) || ids.Contains(x.TargetId)).ExecuteCommandAsync();
            });
            if (!result.IsSuccess)//如果成功了
            {
                throw result.ErrorException;
            }
        }
    }

    #region 方法

    /// <summary>
    /// 检查输入参数
    /// </summary>
    /// <param name="sysResource"></param>
    private async Task<string> CheckInput(SysMenu sysResource)
    {
        var menList = await GetListAsync(x => x.Category == CateGoryConst.Menu_MODULE);

        //判断是否从存在重复模块
        var hasSameName = menList.Any(it => it.Title == sysResource.Title && it.Id != sysResource.Id);
        if (hasSameName)
        {
            return ($"存在重复的模块:{sysResource.Title}");
        }
        //设置为模块
        sysResource.Category = CateGoryConst.Menu_MODULE;

        return "OK";
    }

    #endregion 方法
}